﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace WorkflowAutomation
{
    class WorkflowDetails
    {
		private static readonly string WorkflowsConfigurationFile = Path.Combine(Environment.CurrentDirectory, "Workflows.xml");

		public Guid WorkflowGUID;
		public string WorkflowName;
		public Boolean Enabled;
		public string FetchXML;
		public string PrimaryEntity;

        /// <summary>
        /// This function retrieves all workflow details from Workflows.xml configuration file.
        /// </summary>
        /// <returns></returns>
		public static List<WorkflowDetails> GetWorkflowDetails()
		{
			List<WorkflowDetails> returnList = new List<WorkflowDetails>();

			//read from the Workflows.xml file in the same executable folder.			
			if (File.Exists(WorkflowsConfigurationFile))
			{
				XElement configurationsFromFile = XElement.Load(WorkflowsConfigurationFile);
				foreach (XElement config in configurationsFromFile.Nodes())
				{
					WorkflowDetails newConfig = new WorkflowDetails();

					if (!String.IsNullOrEmpty(config.Element("WorkflowGUID").Value))
					{
						if (!Guid.TryParse(config.Element("WorkflowGUID").Value, out newConfig.WorkflowGUID))
							throw new ApplicationException("WorkflowGUID in Workflows.xml file is not a valid GUID value.");
					}
                    
					if (!String.IsNullOrEmpty(config.Element("Enabled").Value))
						newConfig.Enabled = ParseBoolean(config.Element("Enabled").Value);

					if (!String.IsNullOrEmpty(config.Element("FetchXML").Value))
						newConfig.FetchXML = config.Element("FetchXML").Value;

					returnList.Add(newConfig);
				}
			}
			else
			{
				//prompt user about the error.
				throw new ApplicationException("Workflows.xml file is missing from the executable folder.");
			}
			
			return returnList;
		}

        /// <summary>
        /// Returns true if the string input is true of boolean. Otherwise, false.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
		private static Boolean ParseBoolean(string input)
		{
			if (input == "1")
				return true;
			else if (input == "0")
				return false;
			else
			{
				input = input.ToUpper();
				if (input == "YES" || input == "TRUE")
					return true;
				else if (input == "NO" || input == "FALSE")
					return false;
			}

			throw new ApplicationException("Invalid Boolean value. Valid values are 1, 0, true, false, yes, no.");
		}
    }
}
